package com.lianjia.analysis.util;

import java.util.List;

/**
 * 分析工具类
 */
public class AnalysisUtils {

    /**
     * 计算两个数据集的相关系数
     */
    public static double calculateCorrelation(List<Double> x, List<Double> y) {
        if (x == null || y == null || x.size() != y.size() || x.isEmpty()) {
            return 0;
        }
        
        int n = x.size();
        
        // 计算平均值
        double xMean = x.stream().mapToDouble(Double::doubleValue).average().orElse(0);
        double yMean = y.stream().mapToDouble(Double::doubleValue).average().orElse(0);
        
        // 计算分子
        double numerator = 0;
        for (int i = 0; i < n; i++) {
            numerator += (x.get(i) - xMean) * (y.get(i) - yMean);
        }
        
        // 计算分母
        double xVariance = x.stream().mapToDouble(value -> Math.pow(value - xMean, 2)).sum();
        double yVariance = y.stream().mapToDouble(value -> Math.pow(value - yMean, 2)).sum();
        
        double denominator = Math.sqrt(xVariance * yVariance);
        
        return denominator == 0 ? 0 : numerator / denominator;
    }
    
    /**
     * 将价格文本转换为数值
     */
    public static Double parsePriceText(String priceText) {
        if (priceText == null || priceText.trim().isEmpty()) {
            return null;
        }
        
        try {
            // 移除非数字字符，保留小数点
            String numericText = priceText.replaceAll("[^0-9.]", "");
            return Double.parseDouble(numericText);
        } catch (NumberFormatException e) {
            return null;
        }
    }
    
    /**
     * 将面积文本转换为数值
     */
    public static Double parseAreaText(String areaText) {
        if (areaText == null || areaText.trim().isEmpty()) {
            return null;
        }
        
        try {
            // 移除"平米"等单位，保留数字部分
            String numericText = areaText.replaceAll("[^0-9.]", "");
            return Double.parseDouble(numericText);
        } catch (NumberFormatException e) {
            return null;
        }
    }
} 